const { bfmetaSDK } = require('../../../util/util')
const { signature, isAddress } = require('../../../util/signature')

// 在某个模版上发行某个具体权益实体
const trIssueEntity = () => {
    return async (req, res, next) => {
        try {
            if(!req.body.publicKey || !req.body.factoryId || !req.body.entityId || !req.body.recipientId || !req.body.secretKey){
                return res.status(400).send({
                    success: false,
                    message: "参数不能为空"
                })
            }
            if(typeof req.body.publicKey !== 'string' || typeof req.body.factoryId !== 'string' || typeof req.body.entityId !== 'string' || typeof req.body.recipientId !== 'string' || typeof req.body.secretKey !== 'string'){
                return res.status(400).send({
                    success: false,
                    message: "参数类型必须为string"
                })
            }
            if(!isAddress(req.body.recipientId)){
                return res.status(400).send({
                    success: false,
                    message: "recipientId为非法地址"
                })
            }
            let data={
                publicKey: req.body.publicKey,
                fee: "2000",
                applyBlockHeight: 1,
                factoryId: req.body.factoryId,
                entityId: req.body.entityId,
                recipientId: req.body.recipientId           
            }
            // 创建 发行权益实体事件
            let result = await bfmetaSDK.api.transaction.createIssueEntity(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            // 签名该事件
            const _signature = await signature(result.result.buffer, req.body.secretKey)
            data = {
                signature: _signature,
                buffer: result.result.buffer,
            }
            // 广播 发行权益实体事件
            result = await bfmetaSDK.api.transaction.broadcastIssueEntity(data)
            if(!result.success){
               return res.status(400).send(result)
            }
            res.status(200).send(result)
        } catch (error) {
            next(error)
        }
    }
}

module.exports = {trIssueEntity}